    //
//  RootViewController.m
//  SplunkMobile
//
//  Created by Qixin on 13-9-10.
//  Copyright (c) 2013年 Gome. All rights reserved.
//

#import "RootViewController.h"
#import "GMFDrawingVC.h"
#import "GMFRemarkButton.h"
#import <WebKit/WebKit.h>
#import "SplunkMobile-Swift.h"
#import "GMWaterMarkView.h"


#define screenH   ([UIScreen mainScreen].bounds.size.height)
#define screenW   ([UIScreen mainScreen].bounds.size.width)
#define SP_Gif_Name @"WaitingImage/waiting_7.gif" // 显示动画名称
#define DeviceVerions [[[UIDevice currentDevice] systemVersion] floatValue]

@interface RootViewController ()
<
UIAlertViewDelegate,
WKUIDelegate,
WKNavigationDelegate,
WKScriptMessageHandler
>
{
    CGFloat fltScreenW_;
    CGFloat fltScreenH_;
    
    BOOL isShowWebvAnimation_; // 是否显示flash动画
    
    BOOL isShowActivityIndicator_; // 是否显示菊花等待框
}

@property (nonatomic, strong) WKWebView *wkWebSplunk;
@property (nonatomic, strong) UIWebView *webvAnimation;

@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;

@property (nonatomic, weak) UIButton *btnEdit;

@property (nonatomic, assign) BOOL isDragEnd;

@property (nonatomic, strong) NSString *webTitle;

@property (nonatomic, strong) NSString *currentURL;

@property (nonatomic, assign) BOOL isEditButtonCreated;

@end


@implementation RootViewController


#pragma mark - ******************** View Lifecycle ********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self adapteBackgroundAndStatus]; // 适配背景色和状态栏
    
    [self initVariable]; // 初始化变量
    [self initViews]; // 初始化界面
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _btnEdit.hidden = NO;
}

- (void)viewDidUnload
{
    [self setWkWebSplunk:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    self.wkWebSplunk.UIDelegate = nil;
    self.wkWebSplunk.navigationDelegate = nil;
}


#pragma mark - ******************** Init All Views ********************

- (void)initVariable
{
    fltScreenW_ = [UIScreen mainScreen].bounds.size.width;
    fltScreenH_ = [UIScreen mainScreen].bounds.size.height;
    
    // 使用Flash动画等待框
    isShowWebvAnimation_ = YES;
    
    // 暂时不适用菊花
    isShowActivityIndicator_ = NO;
}

- (void)adapteBackgroundAndStatus
{
    // 背景色为白色
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 做状态栏适配
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
    {
//        self.wantsFullScreenLayout = YES;
    }
    else
    {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)initViews
{
    // 初始化Splunk的WebView
    [self initMainViews];
    
    if (isShowWebvAnimation_)
    {
        // 初始化动画的WebView
        [self initAnimationViews];
    }
    
    if (isShowActivityIndicator_)
    {
        // 初始化提示框
        [self initActivityIndicatorViews];
    }
    
    
    
//    [self initEditButton];
}

- (void)initAnimationViews
{
    CGSize sizeImage = [UIImage imageNamed:SP_Gif_Name].size;
    _webvAnimation = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,sizeImage.width,sizeImage.height)];
    _webvAnimation.backgroundColor = [UIColor clearColor];
    _webvAnimation.opaque = NO;
    _webvAnimation.multipleTouchEnabled = NO;
    _webvAnimation.userInteractionEnabled = NO; // 禁止UIWebView的滚动
    _webvAnimation.transform = CGAffineTransformScale(CGAffineTransformIdentity,0.6,0.6); // 缩小
    _webvAnimation.center = CGPointMake(fltScreenW_ / 2, fltScreenH_ / 2);
    [self.view addSubview:_webvAnimation];
    
    // 加载动画
    NSMutableString* MstrHtmlStr = [NSMutableString string];
    [MstrHtmlStr appendString:@"<p><img src=\""];
    [MstrHtmlStr appendString:SP_Gif_Name];
    [MstrHtmlStr appendString:@"\" alt=\"picture\"/>"];
    [_webvAnimation loadHTMLString:MstrHtmlStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}

- (void)initMainViews
{
    self.wkWebSplunk = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
    __weak typeof(self) weakSelf = self;
    [self.wkWebSplunk evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.minimumFontSize = 18;
        
        NSString *oldAgent = result;
//        NSString *newAgent = [NSString stringWithFormat:@"%@ GomeBigdataAppSim GomeBigdata:%@", oldAgent, [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
        NSString *newAgent = [NSString stringWithFormat:@"%@ GomeBigdata:%@", oldAgent, [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
        // 设置global User-Agent
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        
        strongSelf.wkWebSplunk = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20) configuration:config];
        
        strongSelf.wkWebSplunk.navigationDelegate = self;
        strongSelf.wkWebSplunk.UIDelegate = self;
        strongSelf.wkWebSplunk.scrollView.bounces = NO;
        strongSelf.wkWebSplunk.scrollView.showsVerticalScrollIndicator = NO;
        strongSelf.wkWebSplunk.scrollView.showsHorizontalScrollIndicator = NO;
        strongSelf.wkWebSplunk.opaque = NO;
        
        [strongSelf.view addSubview:strongSelf.wkWebSplunk];
        
        WKUserContentController *userCC = config.userContentController;
        [userCC addScriptMessageHandler:self name:@"login"];
        [userCC addScriptMessageHandler:self name:@"loginOut"];
        
        // 加载URL
        [strongSelf loadWebView:kOnlineURL];
    }];
}

- (void)initActivityIndicatorViews
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _activityIndicator.center = CGPointMake(fltScreenW_ / 2, fltScreenH_ / 2);//只能设置中心，不能设置大小
    _activityIndicator.color = [UIColor redColor]; // 改变圈圈的颜色为红色； iOS5引入
    [_activityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏
    
    [self.view addSubview:_activityIndicator];
}

- (void)initEditButton
{
    GMFRemarkButton *btnEdit = [[GMFRemarkButton alloc] initWithFrame:CGRectMake(screenW - fltButtonWidth - 10 - 10 - 10, screenH - 150, fltButtonWidth + 10 + 20, fltButtonWidth + 10 + 40)];
//    [btnEdit setImage:[UIImage imageNamed:@"btn_drawing-z"] forState:UIControlStateNormal];
    [btnEdit addTarget:self action:@selector(gotoDrawingVC) forControlEvents:UIControlEventTouchUpInside];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [btnEdit addGestureRecognizer:pan];

//    [btnEdit addTarget:self action:@selector(dragMoving:withEvent: )forControlEvents: UIControlEventTouchDragInside];
//    [btnEdit addTarget:self action:@selector(dragEnded:withEvent: )forControlEvents: UIControlEventTouchUpInside |
//     UIControlEventTouchUpOutside];
    
    [self.view addSubview:btnEdit];
    self.btnEdit = btnEdit;
    
    _isEditButtonCreated = YES;
}
#pragma mark  拖拽手势方法
- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer
{
    ///  获取通过的点
    CGPoint p = [gestureRecognizer translationInView:_btnEdit];
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) // 开始滑动
    {
        
    }
    else if ([gestureRecognizer state] == UIGestureRecognizerStateChanged) // 坐标改变中
    {
        if (_btnEdit.frame.origin.x + p.x <= 0 || _btnEdit.frame.origin.x  + p.x >= screenW - _btnEdit.frame.size.width)
        {
            if (_btnEdit.frame.origin.y + p.y <= 20 || self.view.frame.origin.y + p.y >= screenH  - _btnEdit.frame.size.height)
            {
                [_btnEdit setTransform:CGAffineTransformTranslate([self.view transform], 0, 0)];
            }
            else
            {
                [_btnEdit setTransform:CGAffineTransformTranslate([_btnEdit transform], 0, p.y)];
                [gestureRecognizer setTranslation:CGPointZero inView:_btnEdit];
            }
        }
        else if (_btnEdit.frame.origin.y + p.y <= 20 || _btnEdit.frame.origin.y + p.y >= screenH  - _btnEdit.frame.size.height)
        {
            if (_btnEdit.frame.origin.x + p.x <= 0 || _btnEdit.frame.origin.x + p.x >= screenW - _btnEdit.frame.size.width)
            {
                [_btnEdit setTransform:CGAffineTransformTranslate([_btnEdit transform], 0, 0)];
            }
            else
            {
                [_btnEdit setTransform:CGAffineTransformTranslate([_btnEdit transform], p.x, 0)];
                [gestureRecognizer setTranslation:CGPointZero inView:_btnEdit];
            }
        }
        else
        {
            [_btnEdit setTransform:CGAffineTransformTranslate([_btnEdit transform], p.x, p.y)];
            [gestureRecognizer setTranslation:CGPointZero inView:_btnEdit];
        }
        
    }
    else // 手离开屏幕
    {
        if (_btnEdit.frame.origin.x >= screenW / 2.0 - _btnEdit.frame.size.width / 2)
        {
            [UIView animateWithDuration:.3f animations:^{
                _btnEdit.frame = CGRectMake(screenW - _btnEdit.frame.size.width, _btnEdit.frame.origin.y, _btnEdit.frame.size.width, _btnEdit.frame.size.height);
            }];
        }
        else
        {
            [UIView animateWithDuration:.3f animations:^{
                _btnEdit.frame = CGRectMake(0, _btnEdit.frame.origin.y, _btnEdit.frame.size.width, _btnEdit.frame.size.height);
            }];
        }
    }
}

#pragma mark - ******************** Button Touch Event ********************

- (void) dragMoving: (UIControl *) c withEvent:ev
{
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
}

- (void) dragEnded: (UIControl *) c withEvent:ev
{
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
    
//    _isDragEnd = YES;
}

- (void)gotoDrawingVC
{
    if (_isDragEnd)
    {
        _isDragEnd = NO;
        return;
    }
    
    _btnEdit.hidden = YES;
    
//    /// 不支持Retina屏的旧截图方法
//    UIGraphicsBeginImageContext(self.view.bounds.size);
//    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    
    
    UIView *viewFlash = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenW, screenH)];
    viewFlash.backgroundColor = [UIColor blackColor];
    [viewFlash setAlpha:1];
    [self.view addSubview:viewFlash];
    
    __weak typeof(self) _weakSelf = self;
    [_wkWebSplunk swContentCapture:^(UIImage * capturedImage) {
        __strong typeof(self) __StrongSelf = _weakSelf;
        /// 闪烁一下
        [UIView animateWithDuration:0.2 animations:^{
            [viewFlash setAlpha:0];
        } completion:^(BOOL finished) {
            /// 跳转
            GMFDrawingVC *dvc = [[GMFDrawingVC alloc] init];
            dvc.imgScreenshot = capturedImage;
            dvc.shareTitle =__StrongSelf.webTitle.length>0 ?__StrongSelf.webTitle:@" ";
            [__StrongSelf presentViewController:dvc animated:NO completion:^{
                 
            }];
        }];
    }];
    
    /// 截图
//    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);
//    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    
    
}


#pragma mark - ******************** Functions ********************

#pragma mark - Cookie

- (void)lookCookie
{
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies])
    {
        NSLog(@"---->%@\n", cookie);
    }
}

- (void)clearCookie
{
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];
    for (id obj in _tmpArray)
    {
        [cookieJar deleteCookie:obj];
    }
}

#pragma mark - 刷新菊花

- (void)startLoading
{
    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;
    
    if (isShowActivityIndicator_)
    {
        [_activityIndicator startAnimating]; // 开始旋转
    }
}

- (void)endLoading
{
    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = NO;
    
    if (isShowActivityIndicator_)
    {
        [_activityIndicator stopAnimating]; // 结束旋转
    }
    
    if (isShowWebvAnimation_
        && _webvAnimation)
    {
        [_webvAnimation removeFromSuperview]; // 移除动画
        _webvAnimation = nil;
    }
    
}

- (void)loadWebView:(NSString*)url
{
    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:30.0];
    
    [self.wkWebSplunk loadRequest:request];
}


#pragma mark - ******************** Delegate Event ********************
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) // 再来一次
    {
        [self loadWebView:kOnlineURL];
    }
}

#pragma mark - WKNavigationDelegate

/**
 *  页面开始加载时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s", __FUNCTION__);
    [self performSelectorOnMainThread:@selector(startLoading)
                           withObject:nil
                        waitUntilDone:YES];
}

/**
 *  当内容开始返回时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='rgba(255,255,255,0.8)'" completionHandler:nil];
//    [webView evaluateJavaScript:@"document.getElementsByTagName('table').style.background='rgba(255,255,255,0.8)'" completionHandler:nil];
//    NSLog(@"%s", __FUNCTION__);
//    [_progressView setProgress:0.0 animated:false];
    [self performSelectorOnMainThread:@selector(endLoading)
                           withObject:nil
                        waitUntilDone:YES];
    
//    self.webTitle =[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.webTitle = webView.title;
    
    self.currentURL = webView.URL.absoluteString;
    
    if (!_isEditButtonCreated)
    {
        [self initEditButton];
    }
    
    NSLog(@"%@", _currentURL);
    
//    if ( [_currentURL isEqualToString:kOnlineURL]                                      ||
//        [_currentURL isEqualToString:[kOnlineURL stringByAppendingString:@"login"]]   ||
//        [_currentURL isEqualToString:[kOnlineURL stringByAppendingString:@"logout"]]  ||
//        [_currentURL isEqualToString:[kOnlineURL stringByAppendingString:@"seclect"]]
//        )
//    {
//        _btnEdit.hidden = YES;
//    }
//    else
//    {
        _btnEdit.hidden = NO;
//    }
}

/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSLog(@"%s", __FUNCTION__);
    [self performSelectorOnMainThread:@selector(endLoading)
                           withObject:nil
                        waitUntilDone:YES];
    
    // 网络有问题弹出提示框
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSString *strErr = [NSString stringWithFormat:@"网络有问题(%@)", @(error.code)];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:strErr
                                                           delegate:self
                                                  cancelButtonTitle:@"算了吧"
                                                  otherButtonTitles:@"再来一次", nil];
        [alertView show];
    });
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"didReceiveServerRedirect ");
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@" %s,change = %@",__FUNCTION__,change);
//    if ([keyPath isEqual: @"estimatedProgress"] && object == _wkWebView) {
//        [self.progressView setAlpha:1.0f];
//        [self.progressView setProgress:_wkWebView.estimatedProgress animated:YES];
//        if(_wkWebView.estimatedProgress >= 1.0f)
//        {
//            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
//                [self.progressView setAlpha:0.0f];
//            } completion:^(BOOL finished) {
//                [self.progressView setProgress:0.0f animated:NO];
//            }];
//        }
//    }
//    else {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"message = %@", message.name);
    NSDictionary *body = message.body;
    NSLog(@"body = %@", body);
    NSString *methodName = message.name;
    
    GMWaterMarkView *markView = [GMWaterMarkView shareInstance];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([methodName isEqualToString:@"login"]) {
        NSDictionary *userInfo = message.body;
        NSString *userName = [userInfo objectForKey:@"userName"];
       
        [userDefaults setObject:userName forKey:@"splunk_userName"];
        [markView showTheWaterMark];
    }else{
        [userDefaults setObject:@"" forKey:@"splunk_userName"];
        [markView hidenTheWaterMark];
    }
}

@end
